package com.eco.fanliapp.job.hdkitemjob;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.eco.fanliapp.common.constant.ApiEnum;
import com.eco.fanliapp.dao.AppGoodsMapper;
import com.eco.fanliapp.entity.AppCompany;
import com.eco.fanliapp.entity.AppGoods;
import com.eco.fanliapp.entity.CountLauncher;
import com.eco.fanliapp.service.*;
import com.eco.fanliapp.utils.ApiUtils;
import com.eco.fanliapp.utils.DateUtils;
import com.eco.fanliapp.utils.JsonUtils;
import com.eco.fanliapp.utils.StringUtils;
import com.eco.fanliapp.vo.HaoDanKuItemInfo;
import org.quartz.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import java.io.Serializable;
import java.math.BigDecimal;
import java.util.*;


@DisallowConcurrentExecution
@PersistJobDataAfterExecution
public class getHDKTopItemsTask implements Job, Serializable {
    private static final Logger log = LoggerFactory.getLogger(getHDKTopItemsTask.class);
    @Autowired
    private IJobOrderInfoGetService jobOrderInfoGetService;
    @Autowired
    private IAppGoodsService appGoodsService;

    @Autowired
    private IUserCashschemeService userCashschemeService;
    @Autowired
    private ITaoBaoService taoBaoService;
    @Autowired
    private AppGoodsMapper appGoodsMapper;
    @Autowired
    private RedisTemplateService redisTemplateService;
    @Autowired
    private IGoodsImageLableService goodsImageLableService;

    public getHDKTopItemsTask() {
    }

    @Override
    public void execute(JobExecutionContext context) throws JobExecutionException {

        //取得job详情
        JobDetail jobDetail = context.getJobDetail();

        JobDataMap dataMap = jobDetail.getJobDataMap();

        int executeCount = 0;
        if (dataMap.containsKey("runCount")) {
            executeCount = dataMap.getInt("runCount");
        }

        // 增量计数并将其存储回 JobDataMap，这样可以适当保持工作状态
        executeCount++;
        dataMap.put("runCount", executeCount);

        long beginTime = System.currentTimeMillis();
        log.info("***************************************开始执获取好单库商品列表--首页商品 定时任务-getHDKTopItemsTask：executeCount=" + executeCount + "--beginTime=" + beginTime);

        CountLauncher countLauncher = new CountLauncher(10);
        jobOrderInfoGetService.setCountLauncher(countLauncher);
        log.info("开始获取好单库商品开始  0 * */1 * * ?");
        long startMillions = System.currentTimeMillis();
        long min = 1;
        long back = 1000;
        int n = 0;
        java.util.Calendar calendar = java.util.Calendar.getInstance();
        calendar.setTime(new Date());
        int time = calendar.get(java.util.Calendar.HOUR_OF_DAY);
        while (true) {

            Map<String, Object> data = new HashMap<String, Object>();
            data.put("sale_type", "1");
            data.put("item_type", "1");
            data.put("back", back);
            data.put("min_id", min);

            try {
                String str = ApiUtils.getData(ApiEnum.SALES_LIST, data);

//                log.info("获取好单库商品列表数据{}", str);
                JSONObject object = JSONObject.parseObject(str);
                AppGoods response = JsonUtils.getJsonToBean(object.toJSONString(), AppGoods.class);
                if (response != null && response.getCode() == 1) { //code等于1代表请求成功
                    JSONArray array = JSONArray.parseArray(object.getJSONArray("data").toJSONString());
                    List<HaoDanKuItemInfo.DataBean> bean = JsonUtils.getJsonToList(array.toJSONString(), HaoDanKuItemInfo.DataBean.class);
                    if (bean == null || bean.size() <= 0) {
                        break;
                    }
                    AppCompany com = userCashschemeService.findCompanyAll();
                    List<AppGoods> updateAppGoodsList = new ArrayList<>();
                    List<AppGoods> addAppGoodsList = new ArrayList<>();
                    List<AppGoods> AppGoodsList = new ArrayList<>();
                    for (HaoDanKuItemInfo.DataBean haoDanKuItemInfo : bean) {
                        AppGoods dataBean = HDKUtils.getAppGoodsFromHDK(haoDanKuItemInfo);
                        dataBean = appGoodsService.getMoneyInfoByGoodsId(com, dataBean);
//                        if (("80.00").equals(dataBean.getTkrates()) && dataBean.getItemendprice() > 15) {
//                            continue;
//                        }
                        dataBean.setItemType(1);
                        dataBean.setRecommend(1);
//                        if (StringUtils.isNotNull(dataBean.getFqcat())) {
//
//                            if ("5".equals(dataBean.getFqcat())) {
//                                dataBean.setFqcat("3");
//                            }
//                            if ("7".equals(dataBean.getFqcat())) {
//                                dataBean.setFqcat("6");
//                            }
//                            if ("13".equals(dataBean.getFqcat())) {
//                                dataBean.setFqcat("12");
//                            }
//                            if ("16".equals(dataBean.getFqcat())) {
//                                dataBean.setFqcat("15");
//                            }
//                            if ("8".equals(dataBean.getFqcat())) {
//                                dataBean.setFqcat("9");
//                            }
//                        }

//                        if (dataBean.getCouponstarttime() != null
//                                && dataBean.getCouponendtime() != null
//                                && dataBean.getEndTime() != null) {
//                            dataBean.setCouponstarttime(
//                                    dataBean.getCouponstarttime() == null ? "0" :
//                                            dataBean.getCouponstarttime() + "000");
//                            dataBean.setCouponendtime(
//                                    dataBean.getCouponendtime() == null ? "0" :
//                                            dataBean.getCouponendtime() + "000");
//                            dataBean.setStartTime(
//                                    dataBean.getStartTime() == null ? "0" :
//                                            dataBean.getStartTime() + "000");
//                            dataBean.setEndTime(
//                                    dataBean.getEndTime() == null ? "0" :
//                                            dataBean.getEndTime() + "000");
//                            dataBean.setStarttime(
//                                    dataBean.getStarttime() == null ? "0" :
//                                            dataBean.getStarttime() + "000");
//                            dataBean.setTaobaoImage(dataBean.getTaobaoImage() == null ? dataBean.getItempic() : dataBean.getTaobaoImage().replace(" ", ""));


                        //判断是否最终金额小于0
                        BigDecimal itemendprice = new BigDecimal(dataBean.getItemendprice() == null ? 0d : dataBean.getItemendprice());
                        BigDecimal tkMoney = new BigDecimal(dataBean.getTkmoney() == null ? "0" : dataBean.getTkmoney());
                        if ((itemendprice.subtract(tkMoney)).compareTo(new BigDecimal(0)) < 0) {
                            continue;
                        }
                        dataBean.setCreateTime(DateUtils.getNowTimestamp());
                        dataBean.setUpdateTime(DateUtils.getNowTimestamp());
                        dataBean.setAddUserId(-115);
                        dataBean.setSort(n++);
                        AppGoods appGoods = appGoodsMapper.findAppGoodsByItemId(dataBean.getItemid());
                        if (appGoods != null && appGoods.getDeleted() == 1) {
                            continue;
                        }
                        AppGoodsList.add(dataBean);
                        if (appGoods != null) {
                            if (appGoods.getItemTop() == 1 && appGoods.getDeleted() == 0) {
                                updateAppGoodsList.add(dataBean);
                            } else {
                                continue;
                            }
                        } else {
                            addAppGoodsList.add(dataBean);
                        }
                    }

//                    }
                    appGoodsMapper.updateGoods("10000", null,null);
                    if (addAppGoodsList.size() > 0) {
                        try {
                            boolean flag = appGoodsService.saveBatch(addAppGoodsList);
                            if (flag) {
                                log.info("商品拉取--首页商品   入库商品新增成功 size=" + addAppGoodsList.size());
                            } else {
                                log.info("商品拉取--首页商品   入库商品新增失败" + addAppGoodsList.toString());
                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                    if (updateAppGoodsList.size() > 0) {
                        for (AppGoods goods : updateAppGoodsList) {
                            try {
                                int i = appGoodsService.updateBatchByItemId(goods);
                                if (i > 0) {
                                    log.info("商品拉取--首页商品   入库商品更新成功 数据size={} ", updateAppGoodsList.size());
                                } else {
                                    log.info("商品拉取--首页商品   入库商品更新失败 数据={} ", updateAppGoodsList.toString());
                                }
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                        }
                    }
                    appGoodsMapper.updateGoods(null, "0",null);
                    log.info("商品拉取--首页商品  更新数据库刷新缓存");
                    taoBaoService.getRedisRecommendGoodsList(AppGoodsList);
//                    for (int i = 0; i <= 27; i++) {
//                        String keyy = "app_recommendGoodsLists_" + i;
//                        if (redisTemplateService.hasKey(keyy)) {
//                            redisTemplateService.del(keyy);
//                        }
//                    }
//                    redisTemplateService.batchDel("app_recommendGoods_lists" + 20 + "_" + 1,
//                            "app_recommendGoods_lists" + 20 + "_" + 2,
//                            "app_recommendGoods_lists" + 40 + "_" + 1,
//                            "app_recommendGoods_lists" + 40 + "_" + 2);
                } else {
                    log.info("商品拉取--首页商品   请求{}", response.getMsg());
                    break;
                }
                min = response.getMinId();
            } catch (Exception e) {
                e.printStackTrace();
                log.error("商品拉取--首页商品   0 0/3 * * * ? 失败 耗时" + (System.currentTimeMillis() - startMillions) + "   错误=" + e.getMessage());
                break;
            }
        }

        long endTime = System.currentTimeMillis();
        log.info("***************************************结束获取好单库商品列表--首页商品定时任务-getHDKTopItemsTask：executeCount=" + executeCount + "--endTime=" + endTime + "--耗时=" + (endTime - beginTime));

    }
}

